package com.zyb.beidada.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyb.beidada.common.ErrorCode;
import com.zyb.beidada.exception.ThrowUtils;
import com.zyb.beidada.model.dto.question.QuestionContentDTO;
import com.zyb.beidada.model.entity.App;
import com.zyb.beidada.model.entity.Question;
import com.zyb.beidada.model.entity.ScoringResult;
import com.zyb.beidada.model.entity.UserAnswer;
import com.zyb.beidada.model.enums.ScoringStrategyEnum;
import com.zyb.beidada.model.vo.QuestionVO;
import com.zyb.beidada.model.vo.ScoringResultVO;
import com.zyb.beidada.service.QuestionService;
import com.zyb.beidada.service.ScoringResultService;
import com.zyb.beidada.service.UserAnswerService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @author 十八岁讨厌编程
 * @date 2025/5/6 20:02
 * @PROJECT_NAME beidada-backend
 * @description 自定义测评类打分逻辑
 */
@ScoringStrategyRequire(appType = 1, scoringStrategy = 0)
@Component
public class CustomTestScoringStrategy implements ScoringStrategy{

    @Resource
    private ScoringResultService scoringResultService;

    @Resource
    private QuestionService questionService;

    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        //获取结果集
        LambdaQueryWrapper<ScoringResult> scoringResultLambdaQueryWrapper = new LambdaQueryWrapper<>();
        scoringResultLambdaQueryWrapper.eq(ScoringResult::getAppId, app.getId());
        List<ScoringResult> scoringResults = scoringResultService.list(scoringResultLambdaQueryWrapper);
        //创建分数map,并初始化
        HashMap<Long, Integer> scoreMap = new HashMap<>();
        for (ScoringResult scoringResult : scoringResults) {
            scoreMap.put(scoringResult.getId(), 0);
        }
        //创建属性计数map
        HashMap<String, Integer> countMap = new HashMap<>();
        //统计属性数量
        //得到该应用的试题
        Long appId = app.getId();
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        questionLambdaQueryWrapper.eq(Question::getAppId, appId);
        Question question = questionService.getOne(questionLambdaQueryWrapper);
        //根据题目的答案和用户答案进行打分
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDTO> questionContent = questionVO.getQuestionContent();
//        ThrowUtils.throwIf(questionContent.size() != choices.size(), ErrorCode.PARAMS_ERROR, "题目数量和用户答案数量不一致");
        for (int i = 0; i < choices.size(); i++) {
            //此题的内容
            QuestionContentDTO questionContentDTO = questionContent.get(i);
            //拿到此题对应的答案
            for (QuestionContentDTO.Option option : questionContentDTO.getOptions()) {
                String userAnswer = choices.get(i);
                if (option.getKey().equals(userAnswer)) {
                    //如果用户答案和题目答案一致，则计数
                    Integer count = countMap.get(option.getResult());
                    if (count == null) {
                        count = 0;
                    }
                    countMap.put(option.getResult(), count + 1);
                    break;
                }
            }
        }
        //对结果集进行打分
        for (String item : countMap.keySet()) {
            for (ScoringResult scoringResult : scoringResults) {
                ScoringResultVO scoringResultVO = ScoringResultVO.objToVo(scoringResult);
                if (scoringResultVO.getResultProp().contains(item)) {
                    //进行加分
                    Integer count = countMap.get(item);
                    Long resultVOId = scoringResultVO.getId();
                    scoreMap.put(resultVOId,scoreMap.get(resultVOId) + count);
                    break;
                }
            }
        }
        //选取最高分作为结果,如果最高分有多个，则随机选取一个
        Integer maxScore = Collections.max(scoreMap.values());
        ScoringResult result = new ScoringResult();
        for (Long key : scoreMap.keySet()) {
            if (scoreMap.get(key).equals(maxScore)) {
                result = scoringResultService.getById(key);
                break;
            }
        }

        //构造返回体
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setScoringStrategy(ScoringStrategyEnum.CUSTOM.getValue());
        userAnswer.setAppId(app.getId());
        userAnswer.setAppType(app.getAppType());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(result.getId());
        userAnswer.setResultName(result.getResultName());
        userAnswer.setResultDesc(result.getResultDesc());
        userAnswer.setResultPicture(result.getResultPicture());

        return userAnswer;
    }
}
